/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */
package com.github.xiaoymin.map.ext;

import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.map.MapClientConfig;
import com.github.xiaoymin.map.common.MapClientConstants;
import com.github.xiaoymin.map.model.AmapKey;
import com.github.xiaoymin.map.request.amap.AmapGeoRequest;
import com.github.xiaoymin.map.request.amap.AmapRegeoRequest;
import com.github.xiaoymin.map.response.amap.regeo.AmapRegeoInfo;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
 * 高德地图WebApi接口
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a>
 * 2020/09/21 13:21
 * @since:map-client 1.0
 */
public class AmapClient extends AmapAbstractClient {

    Logger logger=LoggerFactory.getLogger(AmapClient.class);

    /**
     * 根据秘钥配置构造高德地图Client
     * @param mapClientConfig 开发配置
     */
    public AmapClient(MapClientConfig mapClientConfig) {
        super(mapClientConfig);
    }

    public void geo(AmapGeoRequest aMapGeoRequest){
    }

    /**
     * 逆地理编码API
     * @param amapRegeoRequest 请求参数
     * @return 逆地理编码结果
     */
    public Optional<AmapRegeoInfo> regeo(AmapRegeoRequest amapRegeoRequest){
        assertNotEmpty(amapRegeoRequest,"逆地理编码API请求对象不能为空");
        AmapKey amapKey=mapClientConfig.getAmapKey();
        String api= MapClientConstants.AMAP_API_REGEO+parameter(amapRegeoRequest.toMap(amapKey),amapKey);
        logger.info("逆地理编码API:{}",api);
        HttpGet get=new HttpGet(api);
        String content=execute(get);
        if (StrUtil.isNotBlank(content)){
            JsonElement jsonElement=jsonParser.parse(content);
            JsonObject jsonObject=jsonElement.getAsJsonObject();
            String status=jsonObject.get("status").getAsString();
            if (StrUtil.equals(status, MapClientConstants.AMAP_RESPONSE_SUCCESS)){
                return Optional.ofNullable(gson.fromJson(jsonObject.get("regeocode"),AmapRegeoInfo.class));
            }
        }
        return Optional.empty();
    }
}
